<template>
  <view class="wallet-page">
    <!-- 顶部背景 -->
    <view class="wallet-header">
      <image class="header-bg" src="/static/Images/wallet/Toubu.png" mode="widthFix"></image>
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/shop/Fanhui.png" mode="aspectFit"></image>
        </view>
        <view class="title">我的余额</view>
      </view>
    </view>
    
    <!-- 佣金卡片 -->
    <view class="wallet-card">
      <view class="card-status">账户资金保障中</view>
      
      <view class="card-amount-label">可用余额（元）</view>
      <view class="card-amount">{{ displayBalance }}</view>
      
      <button class="withdraw-btn" @click="handleWithdraw">充值</button>
    </view>
    
    <!-- 佣金记录标签 -->
    <view class="record-tabs">
      <view class="tab" :class="{active: activeTab === 'all'}" @click="switchTab('all')">全部</view>
      <view class="tab" :class="{active: activeTab === 'consumption'}" @click="switchTab('consumption')">消费记录</view>
      <view class="tab" :class="{active: activeTab === 'recharge'}" @click="switchTab('recharge')">充值记录</view>
      <view class="tab" :class="{active: activeTab === 'refund'}" @click="switchTab('refund')">退款记录</view>
      <view class="date-filter" @click="showDatePicker">
        <image class="date-icon" src="/static/Images/wallet/Time.png" mode="aspectFit"></image>
        <text class="date-text">日期</text>
      </view>
    </view>
    
    <!-- 交易记录列表 -->
    <view class="record-list">
      <view v-if="filteredRecords.length === 0" class="empty-records">
        <text>暂无相关记录</text>
      </view>
      <view v-else v-for="(record, index) in filteredRecords" :key="record.id" class="record-item">
        <view class="record-left">
          <view class="record-title">{{ record.title }}</view>
          <view class="record-subtitle">{{ record.subtitle }}</view>
          <view class="record-time">{{ record.time }}</view>
        </view>
        <view class="record-amount" :class="{ positive: record.isPositive, negative: !record.isPositive }">
          {{ record.amount }}
        </view>
      </view>
    </view>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 当前激活的标签
const activeTab = ref('all');

// 动态展示的余额
const balance = ref(0);
const displayBalance = computed(() => {
  const num = Number(balance.value) || 0;
  return num.toFixed(2);
});

// 接收来自上一页的 eventChannel 传值
onLoad(() => {
  try {
    console.log('开始获取余额数据');
    
    // 检查是否在小程序环境且 getOpenerEventChannel 可用
    if (typeof getOpenerEventChannel !== 'undefined') {
      const eventChannel = getOpenerEventChannel();
      if (eventChannel && eventChannel.on) {
        console.log('使用 eventChannel 获取余额数据');
        eventChannel.on('initBalance', (data) => {
          console.log('接收到余额数据:', data);
          if (data && typeof data.balance !== 'undefined') {
            balance.value = Number(data.balance) || 0;
            console.log('设置余额为:', balance.value);
          }
        });
      } else {
        console.log('eventChannel 不可用，尝试从本地存储读取');
        // 兜底从本地缓存读取
        uni.getStorage({
          key: 'latest_balance',
          success: (res) => {
            balance.value = Number(res.data) || 0;
            console.log('从本地存储读取余额:', balance.value);
          },
          fail: () => {
            console.log('本地存储中无余额数据');
          }
        });
      }
    } else {
      console.log('H5 环境，直接从本地存储读取余额');
      // H5 环境下直接从本地缓存读取
      uni.getStorage({
        key: 'latest_balance',
        success: (res) => {
          balance.value = Number(res.data) || 0;
          console.log('H5 环境从本地存储读取余额:', balance.value);
        },
        fail: () => {
          console.log('H5 环境本地存储中无余额数据');
        }
      });
    }
  } catch (e) {
    console.error('获取余额数据失败:', e);
    // 兜底从本地缓存读取
    uni.getStorage({
      key: 'latest_balance',
      success: (res) => {
        balance.value = Number(res.data) || 0;
        console.log('异常情况下从本地存储读取余额:', balance.value);
      },
      fail: () => {
        console.log('本地存储中无余额数据');
      }
    });
  }
});

// 所有交易记录数据
const records = ref([
  {
    id: 1,
    title: '账户提现',
    subtitle: '提现成功！',
    time: '2025-04-22 00:59:00',
    amount: '-¥281.53',
    type: 'withdraw',
    isPositive: false
  },
  {
    id: 2,
    title: '订单消费',
    subtitle: '商品购买',
    time: '2025-04-22 00:59:00',
    amount: '-¥17.11',
    type: 'consumption',
    isPositive: false
  },
  {
    id: 3,
    title: '账户充值',
    subtitle: '充值成功！',
    time: '2025-04-22 00:59:00',
    amount: '+¥100.00',
    type: 'recharge',
    isPositive: true
  },
  {
    id: 4,
    title: '订单消费',
    subtitle: '商品购买',
    time: '2025-04-22 00:59:00',
    amount: '-¥17.11',
    type: 'consumption',
    isPositive: false
  },
  {
    id: 5,
    title: '订单消费',
    subtitle: '商品购买',
    time: '2025-04-22 00:59:00',
    amount: '-¥17.11',
    type: 'consumption',
    isPositive: false
  },
  {
    id: 6,
    title: '订单退款',
    subtitle: '退款成功！',
    time: '2025-04-22 00:59:00',
    amount: '+¥35.00',
    type: 'refund',
    isPositive: true
  }
]);

// 根据当前标签过滤记录
const filteredRecords = computed(() => {
  if (activeTab.value === 'all') {
    return records.value;
  } else {
    return records.value.filter(record => record.type === activeTab.value);
  }
});

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 处理提现
const handleWithdraw = () => {
  uni.navigateTo({
    url: '/pages/wallet/recharge'
  });
};

// 显示日期选择器
const showDatePicker = () => {
  uni.showToast({
    title: '日期筛选功能开发中',
    icon: 'none'
  });
};
</script>

<style lang="scss">
.wallet-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.wallet-header {
  position: relative;
  width: 100%;
  height: 200rpx;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 80rpx;
  padding: 80rpx 30rpx 0 30rpx;
  width: 100%;
  box-sizing: border-box;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  user-select: none;
  transition: opacity 0.2s ease;
}

.back-btn:hover {
  opacity: 0.8;
}

.back-btn:active {
  opacity: 0.6;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  flex: 1;
  text-align: center;
  margin-right: 60rpx;
}

/* 佣金卡片 */
.wallet-card {
  margin: -40rpx 30rpx 0;
  padding: 30rpx;
  position: relative;
  z-index: 3;
  margin-top: 2.25rem;
}

.card-status {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.card-amount-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.card-amount {
  font-size: 80rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.withdraw-btn {
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 100rpx;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border: none;
}

/* 记录标签 */
.record-tabs {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 30rpx;
  position: relative;
}

.tab {
  font-size: 30rpx;
  color: #666;
  margin-right: 40rpx;
  position: relative;
  padding-bottom: 10rpx;
}

.tab.active {
  color: #ff4d4f;
  font-weight: 500;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4rpx;
  background-color: #ff4d4f;
  border-radius: 2rpx;
}

.date-filter {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.date-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.date-text {
  font-size: 28rpx;
  color: #666;
}

/* 记录列表 */
.record-list {
  background-color: #fff;
  padding: 0 30rpx;
}

.record-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eee;
}

.record-left {
  flex: 1;
}

.record-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.record-subtitle {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.record-time {
  font-size: 24rpx;
  color: #999;
}

.record-amount {
  font-size: 36rpx;
  font-weight: 500;
  align-self: center;
}

.positive {
  color: #ff4d4f;
}

.negative {
  color: #52c41a;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>